<template>
  <view class="container">
    <ve-navbar style="position: relative; z-index: 100" :title="selector.listPage.title" :autoBack="false" @leftClick="close">
      <template #right>
        <view class="header-right" @click="onOperationClick" v-if="selector.operation">
          <text class="iconfont ve-icon-add" style="font-size: 36rpx; margin-right: 8rpx"></text>
          新增车型
        </view>
        <!-- 右上按钮 -->
        <template v-if="selector.config.extraButton">
          <!-- 新增供应商 -->
          <AddNewSupplier
            v-if="selector.config.extraButton.type == 'addNewSupplier'"
            :config="selector.config.extraButton"
            @success="getList"
          />
        </template>
      </template>
    </ve-navbar>
    <ve-search-bar v-if="selector.config.search !== false" :placeholder="selector.listPage.placeholder" @search="getList" />

    <scroll-view class="scroll-cont" scroll-y>
      <template v-for="item in list" :key="item.key">
        <StaffItem v-if="selector.config.component == 'staff'" :record="item" :selected="setSelected(item)" @click="chooseItem(item)">
        </StaffItem>
        <OrderItem v-else-if="selector.config.component == 'order'" :record="item" :selected="setSelected(item)" @click="chooseItem(item)">
        </OrderItem>
        <CarVehicle
          v-else-if="selector.config.component == 'carVehicle'"
          :record="item"
          :selected="setSelected(item)"
          @click="chooseItem(item)"
        >
        </CarVehicle>
        <Default v-else :record="item" :selected="setSelected(item)" @click="chooseItem(item)"> </Default>
      </template>
      <ve-empty text="没有数据~" v-if="list.length == 0 && loading == false" />
      <ve-gap size="2"></ve-gap>
    </scroll-view>
    <ve-bottom-box size="mini" v-if="list.length > 0">
      <ve-button type="primary" @click="onConfirm" size="long">确认</ve-button>
    </ve-bottom-box>

    <!-- 加载中tip -->
    <ve-toast ref="toastRef"></ve-toast>
  </view>
</template>

<script lang="ts" setup>
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import { nextTick, ref, reactive, getCurrentInstance } from 'vue'
  import Configs from '../../components/remote-select/configs'
  import Default from '../../components/remote-select/items/default.vue'
  import StaffItem from '../../components/remote-select/items/staff.vue'
  import OrderItem from '../../components/remote-select/items/order.vue'
  import CarVehicle from '../../components/remote-select/items/carVehicle.vue'

  // 新增供应商
  import AddNewSupplier from '../../components/remote-select/extra-button/addNewSupplier.vue'

  const _this = getCurrentInstance().proxy

  const statusBarHeight = ref(0)
  onShow(() => {
    uni.getSystemInfo({
      success: function (res) {
        statusBarHeight.value = res.statusBarHeight
      },
    })
  })

  const selector = reactive({
    listPage: {
      title: undefined,
      placeholder: undefined,
    },
    config: {
      search: false,
    },
    params: {},
    prop: undefined,
    operation: false,
    required: false,
  })
  const selectValue = ref()
  const onOperationClick = () => {
    eventChannel.emit('operationClick')
  }
  /**
   * 点击
   */
  const onCreateClick = () => {}
  // 是否是多选
  const isMultiple = ref(false)
  let eventChannel: any
  let disabledValue: string
  onLoad(async ({ title }) => {
    await nextTick()
    if (!_this) return
    eventChannel = _this.getOpenerEventChannel()
    // 监听selectorInit事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('selectorInit', (data: any) => {
      const config = {
        ...Configs[data.type],
        ...data.config,
      }
      selector.config = config
      selector.listPage = config.listPage
      if (title) {
        selector.listPage.title = title
      }
      selector.prop = data.prop
      selector.operation = data.operation
      selector.required = data.required
      selector.params = { ...config.params, ...data.params }
      isMultiple.value = data.multiple
      selectValue.value = data.value
      disabledValue = data.disabledValue
      // 获取列表, 外部传入，或调api
      if (data.outData) {
        getData(data.outData)
        return
      }
      getList()
    })
  })

  // 加载list before
  const list = ref([])
  // 加载外部传入list
  const getData = (data) => {
    loading.value = false
    list.value = data.map((item: any) => {
      const config = selector.config as any
      const sitem = {
        key: item[config.key],
        label: item[config.label],
        desc: undefined,
        option: item,
      }
      if (config.desc) {
        sitem.desc = item[config.desc]
      }
      return sitem
    })
  }

  // 加载list
  const toastRef = ref()
  const loading = ref(true)
  const getList = (keyword = undefined) => {
    const queryParam = {
      ...selector.params,
    }
    queryParam[selector.config.keyword] = keyword

    toastRef.value.showLoading()
    selector.config
      .api(queryParam)
      .then((res: any) => {
        if (res.code == 200) {
          let selectData = res.result.data && res.result.data.length >= 0 ? res.result.data : res.result
          list.value = selectData.map((item: any) => {
            const config = selector.config as any
            const sitem = {
              key: item[config.key],
              label: config.labelFn ? config.labelFn(item) : item[config.label],
              desc: undefined,
              option: { ...item, statusName: item.statusName ?? item.statusStr },
            }
            if (config.desc) {
              sitem.desc = item[config.desc]
            }
            return sitem
          })
          list.value = list.value.filter((it: any) => it.key != disabledValue)
        }
      })
      .finally(() => {
        toastRef.value.hideLoading()
        loading.value = false
      })
  }
  // end

  // const onRightClick = () => {
  //   // emits('rightClick')
  // }

  const setSelected = (item: any) => {
    if (!selectValue.value) return false
    if (Array.isArray(selectValue.value)) {
      return selectValue.value.includes(item.key)
    } else if (item.key == selectValue.value) {
      return true
    }
    return false
  }

  // 选中一个
  const chooseItem = (record: any) => {
    if (isMultiple.value) {
      if (!selectValue.value) {
        selectValue.value = [record.key]
      }
      const index = selectValue.value.findIndex((it: any) => it == record.key)
      if (index == -1) {
        selectValue.value.push(record.key)
      } else {
        selectValue.value.splice(index, 1)
      }
    } else {
      if (selectValue.value == record.key) {
        selectValue.value = undefined
        return
      }
      selectValue.value = record.key
    }
  }

  const onConfirm = () => {
    // 请选择
    if (selector.required && !selectValue.value) {
      uni.showToast({
        title: '请选择',
        icon: 'none',
      })
      return
    }
    if (isMultiple.value) {
      const selectedList = list.value.filter((it: any) => {
        return selectValue.value.includes(it.key)
      })
      const label = selectedList.map((it: any) => it.label).join(' | ')
      const options = selectedList.map((it: any) => it.option)
      eventChannel.emit('selectorConfirm', selectValue.value, label, options)
    } else {
      const record = list.value.find((item: any) => item.key == selectValue.value) || {}
      eventChannel.emit('selectorConfirm', selectValue.value, record.label, record.option)
    }
    uni.navigateBack()
  }

  const close = () => {
    uni.navigateBack()
  }
</script>

<style lang="less" scoped>
  .container {
    height: 100vh;
    width: 100%;
    background: #f7f8fa;

    .header {
      position: relative;
      height: 88rpx;
      background: #ffffff;
      text-align: center;
      .back-btn {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 24px;
      }

      &-right {
        display: flex;
        align-items: center;
        font-size: 30rpx;
        font-weight: 400;
        color: #165dff;

        .svg-icon {
          margin-right: 8rpx;
        }
      }
    }

    .scroll-cont {
      // padding: 1px 0;
    }
  }

  .client-item {
    position: relative;
    background: #ffffff;
    box-shadow: 0rpx 0rpx 30rpx 0rpx rgba(0, 0, 0, 0.05);
    border-radius: 8rpx;
    padding: 32rpx;
    margin: 24rpx;

    .choose {
      position: absolute;
      top: 36rpx;
      right: 32rpx;
    }

    .m_name {
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
      line-height: 44rpx;
      font-size: 32rpx;
    }

    .m_phone {
      margin-top: 16rpx;
      font-size: 28rpx;
      font-weight: 400;
      color: #8491a8;
      line-height: 40rpx;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
</style>
